#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <signal.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <cstring>
#include "client_socket.h"
#include "common_gestor_envios.h"
#define SHUTDOWN 2

using std::cerr;
using std::endl;
using std::string;

Client_socket::Client_socket(int port, char* ip) {
    fd = socket(AF_INET, SOCK_STREAM, 0);
    //gestor = new Gestor_envios();
    addr.sin_family = AF_INET; // Ordenación de bytes de la máquina
    addr.sin_port = htons(port); // Ordenación de bytes de la red
    addr.sin_addr.s_addr = inet_addr(ip); // Direccion IP del server
    memset(&(addr.sin_zero), '\0', 8); // Poner a cero el resto
    if (fd == -1) {
        cerr << "client socket create" << endl;
    }
}

Client_socket::Client_socket() {
}

Client_socket::~Client_socket() {
}

int Client_socket::get_fd() {
    return fd;
}

struct sockaddr_in Client_socket::get_addr() {
    return addr;
}

int Client_socket::conectar() {
    if (connect(fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)) == -1) {
        cerr << "client socket connect" << endl;
        return -1;
    }
    return 0;
}

int Client_socket::enviar(string buffer, int tam) {
    return gestor->enviar(fd, buffer, tam);
}

int Client_socket::recibir(string* buffer, int tam) {
    return gestor->recibir(fd, buffer, tam);
}

void Client_socket::cerrar() {
    close(fd);
}

void Client_socket::cerrar_conexion() {
    if (shutdown(fd, SHUTDOWN) == -1) {
        cerr << "client socket shutdown" << endl;
    }
}
